package xiaohong.thread;

import java.util.concurrent.*;

public class ThreadLocalLeakExample {

    private static ThreadLocal<String> threadLocal = new ThreadLocal<>();

    public static void main(String[] args) {
        ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 5,
                5L,
                TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>(),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy());
//        ExecutorService executor = Executors.newFixedThreadPool(2);
        // 提交第一个任务，设置 ThreadLocal 值
        executor.submit(() -> {
            try {
                threadLocal.set("User A");
                System.out.println(Thread.currentThread().getName() + " set value: " +
                        threadLocal.get());
            } finally {
                threadLocal.remove();
            }
        });

//        try {
//            Thread.sleep(1000);
//        } catch (InterruptedException e) {
//            throw new RuntimeException(e);
//        }
        // 提交第二个任务，但线程池复用了第一个线程，可能导致值污染
        executor.submit(() -> {
            try {
                System.out.println(Thread.currentThread().getName() + " get value: " +
                        threadLocal.get());
            } finally {
                threadLocal.remove();
            }
        });

        executor.shutdown();
    }

}
